package main

import (
	"fmt"
	"github.com/prometheus/common/log"
	"github.com/spf13/cobra"
	"ihub/agent/pkg/tpl"
	"ihub/agent/pkg/writer"
	"ihub/pkg/root"
	"ihub/pkg/utils/flag"
	"os"
	"os/exec"
	"text/template"

	//_"github.com/jteeuwen/go-bindata/go-bindata"
)

var (
	stop = make(chan error,1)
	cmd string
	eds string
	backend string
	extPort string
	agentCmd = &cobra.Command{
		Use:   "agent",
		Short: "nginx agent",
		RunE: func(c *cobra.Command, args []string) error {
			flag.PrintFlags(c.Flags())
			CreateFile("default.conf")
			CreateFile("nginx-ext.conf")
			cmd := exec.Command("/bin/sh","-c",
				cmd,
			)
			cmd.Stdout=&writer.StdOutWrapper{W:os.Stdout,Eds:eds}
			cmd.Stderr=&writer.StdOutWrapper{W:os.Stderr,Eds:eds}
			cmd.Start()
			cmd.Wait()
			return nil
		},
	}
)

func main()  {
	root.Run()
}
func init() {
	agentCmd.PersistentFlags().StringVar(&cmd, "c", "echo ok", "sh cmd")
	agentCmd.PersistentFlags().StringVar(&eds, "eds", "http://127.0.0.1:8080/event2", "cloud event endpoints")
	agentCmd.PersistentFlags().StringVar(&backend, "b", "http://192.168.1.2:5000", "docker registry endpoints")
	root.RootCmd.AddCommand(agentCmd)
}

func CreateFile(conf string) error{
	t :=template.New("test")

	tplBindata,_:=tpl.Asset("agent/pkg/tpl/"+conf)

	t,err :=t.Parse(string(tplBindata))
	if err != nil {
		log.Error(err)
		panic(err)
	}else{
		outputFile, err := os.Create("/etc/nginx/conf.d/"+conf)
		if err != nil {
			return err
		}
		defer func() { _ = outputFile.Close() }()
		err=t.Execute(outputFile, backend)
		if err != nil {
			fmt.Println(err)
			return err
		}
	}
	return nil
}
